#include "controller.h"
#include <opencv2/freetype.hpp>

MatWrapper LogicThread::fetchNextFrame() {
    std::unique_lock<std::mutex> lock(queue_mutex);
    pic_cond.wait(lock, [&] { 
        return !img_queue.empty() || stopProcessing; 
    });

    if (stopProcessing && img_queue.empty()) 
        return {};

    auto frame = img_queue.front();
    img_queue.pop();

    if (img_queue.size() >= 32)
        while (!img_queue.empty())
            img_queue.pop();

    // qDebug() << "Queue Size: " << img_queue.size();

    return frame;
}

#ifdef __USE_CUDA_WARD_SENSE__
std::vector<DL_RESULT> LogicThread::processWithCuda(MatWrapper& mat_wrapper, int counter_id) {
    return CudaManager::getInstance().processWithCuda(mat_wrapper);
}
#endif

cv::Point calculateTextPosition(const cv::Mat& mat, const cv::Rect& box,
                                            int fontFace, double fontScale, int thickness) {
    constexpr int SAFE_MARGIN = 5;
    std::string dummy_label = "Test"; // 用于计算文字高度
    int baseline = 0;
    cv::Size text_size = cv::getTextSize(dummy_label, fontFace, 
                                        fontScale, thickness, &baseline);

    cv::Point pos(box.x, box.y - SAFE_MARGIN);
    if (pos.y < text_size.height) {
        pos.y = box.y + box.height + text_size.height + SAFE_MARGIN;
    }
    return pos;
}

#ifdef __USE_CUDA_WARD_SENSE__
void LogicThread::drawDetectionResults(cv::Mat& mat, const DL_RESULT& result) {
    const cv::Scalar BOX_COLOR(0, 255, 0); // Green
    const cv::Scalar TEXT_COLOR(255, 255, 255); // White
    constexpr int BOX_THICKNESS = 2;
    constexpr int FONT_FACE = cv::FONT_HERSHEY_SIMPLEX;
    constexpr double FONT_SCALE = 1.5;
    constexpr int TEXT_THICKNESS = 2;

    // 绘制边界框
    cv::rectangle(mat, result.box, BOX_COLOR, BOX_THICKNESS);

    // 文字处理
    std::string label = CudaManager::getInstance().getModel()->classes[result.classId];
    cv::Point text_pos = calculateTextPosition(mat, result.box, FONT_FACE, FONT_SCALE, TEXT_THICKNESS);
    
    cv::putText(mat, label, text_pos, FONT_FACE,
                FONT_SCALE, TEXT_COLOR, TEXT_THICKNESS);
}
#endif

void LogicThread::run() {
    QElapsedTimer detectTimer;
    int detectCount = 0;
    double currentRate = 0.0;

    detectTimer.start();

    while (!stopProcessing) {
        MatWrapper frame = fetchNextFrame();
        if (frame.mat.empty()) 
            continue;

#ifdef __USE_CUDA_WARD_SENSE__
        if (counter[frame.id] % DETECT_FRAME_STRIDE == 0) {
            cam_acting_res[frame.id] = processWithCuda(frame, frame.id);
            ++detectCount;
        }
        counter[frame.id]++;
    
        for (auto& result : cam_acting_res[frame.id])
            drawDetectionResults(frame.mat, result);
#endif
        
        cv::Ptr<cv::freetype::FreeType2> ft2 = cv::freetype::createFreeType2();
        ft2->loadFontData("resource/Font/STSONG.TTF", 0);

        if (!frame.mat.empty()) {
            // const std::string cameraText = "Cam-" + std::to_string(frame.id);
            std::string cameraText;
            switch (frame.id) {
            case 0:
                cameraText = "东南"; break;
            case 1:
                cameraText = "东北"; break;
            case 2:
                cameraText = "西南"; break;
            case 3:
                cameraText = "西北"; break;
            default:
                cameraText = "Cam-" + std::to_string(frame.id);
            }
            
            // 计算文本位置（右上角，留出边距）
            int fontFace = cv::FONT_HERSHEY_SIMPLEX;
            double fontScale = 1.2;  // 字体大小
            int fontHeight = 30;  // 字体大小
            int thickness = 1;
            int baseline = 0;
            cv::Size textSize = cv::getTextSize(cameraText, fontFace, fontScale, thickness, &baseline);
            
            // 计算坐标
            int margin = 10;  // 边距
            cv::Point textOrg(frame.mat.cols - textSize.width - margin, 
                            textSize.height + margin);

            // 白色文字
            ft2->putText(frame.mat, cameraText, textOrg, fontHeight,
                         cv::Scalar(255, 255, 255), thickness, cv::LINE_AA, true);
        }

        if (!frame.mat.empty())
            emit frameReady(mat2qimg(frame.mat), frame.id);

        // 每秒计算一次
        if (detectTimer.elapsed() >= 1000) {
            currentRate = static_cast<double>(detectCount) / (detectTimer.elapsed() / 1000.0);
            qDebug() << "Current detect per second:" << currentRate;

            // 重置计时器和计数器
            detectTimer.restart();
            detectCount = 0;
        }
    }
}
